# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :LogHandler.py
# @Time      :2022/3/19 0:06
# @Author    :Yongbo Zhou
import threading
from concurrent.futures.thread import ThreadPoolExecutor
from queue import Queue

import threadpool

from data import db
from tools.FileOpt import read_now_file, read_file
from tools.report_handler import decode

map_types = {
    1: 'car_full_info',  # 整车数据
    2: 'drive_motor',  # 驱动电机
    3: 'fuel_battery',  # 燃料电池
    4: 'engine_data',  # 发动机部分数据
    5: 'car_gps',  # 车辆位置数据
    6: 'extreme_value',  # 极值数据
    7: 'police_data',  # 报警数据
    8: 'charging_device_voltage',  # 可充电储能装置电压数据格式和定义
    9: 'charging_device_temperature',  # 可充电储能装置温度
}


def ii_data(data):
    if data is None:
        return
    report_info = data[0]
    report_subs = data[1]
    info_id = db.insert_dict('report_info', report_info)
    index = 1
    for report_sub in report_subs:
        report_sub['order_no'] = index
        report_sub['info_id'] = info_id
        # del report_sub['offset']
        report_sub.pop('check_code', None)
        report_sub.pop('offset', None)
        report_sub.pop('report_hex_info', None)
        db.insert_dict(map_types[report_sub['msg_type']], report_sub)
        index = index + 1
    pass


def log_handler(path: str, vin_code: str = None):
    path_arr = read_now_file(path)
    qe = Queue(1000000)

    pool = ThreadPoolExecutor(max_workers=50, thread_name_prefix='Thread')

    def consume():
        while True:
            data = qe.get(timeout=3)
            # print(qe.qsize())
            pool.submit(lambda: ii_data(data))
            # ii_data(data)
            qe.task_done()
        pass

    threading.Thread(target=consume).start()

    def pr(file_path):
        print("开始解析文件:", file_path)
        for log_str in read_file(file_path):
            try:
                data = decode(log_str, vin_code)
                if data is not None:
                    qe.put(data)
            except Exception as e:
                print(log_str)
                raise e
        print("文件解析完毕:", file_path)
        # 初始化线程池(商会)，定义好池里最多有几个工人

    [(pr(file_path)) for file_path in path_arr]

    #
    # pool = threadpool.ThreadPool(len(path_arr))
    # requests = threadpool.makeRequests(pr, path_arr)
    # [pool.putRequest(req) for req in requests]
    # pool.wait()
    # for file_path in path_arr:

    pass


if __name__ == '__main__':
    # log_handler('D:\msg-log', vin_code='LSJE36097MS144796')
    log_handler('D:\msg-log')
